import axios from 'axios'
import { useCookie } from '#app'

export default defineNuxtPlugin(() => {
    // 创建axios实例
    const axiosInstance = axios.create({
        baseURL: '/api',
        timeout: 10000,
        headers: {
            'Content-Type': 'application/json'
        }
    })

    // 请求拦截器
    axiosInstance.interceptors.request.use(
        (config) => {
            // 可以在这里添加认证token等
            const token = useCookie('token').value
            if (token) {
                config.headers.Authorization = `Bearer ${token}`
            }
            return config
        },
        (error) => {
            return Promise.reject(error)
        }
    )

    // 响应拦截器
    axiosInstance.interceptors.response.use(
        (response) => {
            // 统一处理响应数据
            return response.data
        },
        (error) => {
            // 统一错误处理
            console.error('API请求错误:', error)
            // 可以在这里添加错误提示、登录过期处理等
            return Promise.reject(error)
        }
    )

    // 文件上传方法
    const uploadFile = async (url: string, file: File, onProgress?: (progress: number) => void) => {
        const formData = new FormData()
        formData.append('file', file)
        try {
            const response = await axiosInstance.post(url, formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                },
                timeout: 6000000,
                onUploadProgress: (progressEvent) => {
                    if (onProgress && progressEvent.total) {
                        const percentCompleted = Math.round(
                            (progressEvent.loaded * 100) / progressEvent.total
                        )
                        onProgress(percentCompleted)
                    }
                }
            })
            return response
        } catch (error) {
            console.error('文件上传错误:', error)
            throw error
        }
    }

    // 提供全局访问
    return {
        provide: {
            axios: axiosInstance,
            uploadFile
        }
    }
})